package com.qinyeit.codegen;

import com.qinyeit.codegen.entity.Column;
import com.qinyeit.codegen.entity.Table;
import jetbrick.io.IoUtils;
import jetbrick.util.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class GenUtils {


	/**
	 * 将下划线命名的字符串转换为驼峰式
	 * hump:(). <br/>
	 *
	 * @return className
	 * @since JDK 1.7
	 */
	public static String hump(String className){
		StringBuilder result = new StringBuilder();
		if (className == null || className.isEmpty()) {
			return "";
		} else if (!className.contains("_")) {
			return className.substring(0, 1).toLowerCase() + className.substring(1);
		}

		String camels[] = className.split("_");
		for (String camel :  camels) {
			if (camel.isEmpty()) {
				continue;
			}
			if (result.length() == 0) {
				result.append(camel.toLowerCase());
			} else {
				result.append(camel.substring(0, 1).toUpperCase());
				result.append(camel.substring(1).toLowerCase());
			}
		}
		return result.toString();
	}

	/**
	 * caseOne:(将字符串第一个字母大写或小写). <br/>
	 *
	 * @param name 名字
	 * @param type (true):toUpper (false):toLower
	 * @since JDK 1.7
	 */
	public static String toCaseOne(String name, boolean type){
		if (name == null || name.isEmpty()) {
			return "";
		}
		return (type?name.substring(0, 1).toUpperCase():name.substring(0, 1).toLowerCase())+name.substring(1);
	}

	/**
	 * 将PD生成sql的文件转换成table
	 * convert:(这里用一句话描述这个方法的作用). <br/>
	 *
	 * @param sql sql
	 * @since JDK 1.7
	 */
	public static Table convert(String sql){
		sql = sql.toLowerCase();

		sql = sql.substring(sql.indexOf("create table "));
		sql = sql.replaceAll("[ ]{2,}", " ");

		String tableName = sql.substring("create table ".length(), sql.indexOf("(")).trim();

		String tempSql = sql.substring(sql.indexOf("(")+1, sql.lastIndexOf(")"));

		String [] columns = tempSql.split(",\n");
		String columnSql;
		List<Column> list = new ArrayList<>();
		Column columnEn ;

		String columnName ;
		String columnType;
		String defaultValue;
		int columnLen;
		String columnDesc ;
		String columnComment ;
		for (int i=0;i<columns.length;i++) {
			columnSql = columns[i].trim();
			if(i==0 || columnSql.contains("primary key")){
				continue;
			}

			columnComment = "";
			columnDesc = "";

			columnName = columnSql.substring(0, columnSql.indexOf(" "));

			columnSql = columnSql.substring(columnSql.indexOf(" ")+1);

			columnType = columnSql.substring(0, columnSql.indexOf(" "));

			//截取列数据长度和列类型
			if(columnType.contains("(")){
				columnLen = Integer.parseInt(columnType.substring(columnType.indexOf("(")+1, columnType.indexOf(")")));
				columnType = columnType.substring(0, columnType.indexOf("("));
			}else{
				columnLen = 0;
			}

			//截取注释部分
			if(columnSql.contains("comment")){
				columnComment = columnSql.substring(columnSql.indexOf("comment ")+"comment ".length()+1, columnSql.length()-1);

				if(columnComment.contains("@@")){
					String [] comment = columnComment.split("@@");
					columnComment = comment[0];
					columnDesc = comment[1];
				}
			}

			columnEn = new Column(columnName, columnType, columnLen, columnComment, columnDesc);

			//不可为空
			if(columnSql.contains("not null")){
				columnEn.setNotNull(true);
			}

			//默认值
			if(columnSql.contains("default")){
				defaultValue = columnSql.substring(columnSql.indexOf("default ")+"default ".length());

				defaultValue = defaultValue.substring(0, defaultValue.indexOf("comment")-1);
				if(defaultValue.contains("\'")){
					defaultValue = defaultValue.replace('\'', '\"');
				}
				columnEn.setDefaultValue(defaultValue);
			}
			list.add(columnEn);
		}

		String tableComment = "";
		String tempUpdateTableComment = "alter table "+tableName+" comment";
		if(sql.contains(tempUpdateTableComment)){
			tableComment = sql.substring(sql.indexOf(tempUpdateTableComment)+tempUpdateTableComment.length());
			tableComment = tableComment.substring(1, tableComment.indexOf(";"));
		}

		Table table = new Table();
		table.setName(tableName);
		table.setDrop(true);
		table.setColumns(list);
		if(StringUtils.isNotBlank(tableComment)){
			table.setComment(tableComment.substring(1, tableComment.length()-1));
		}
		return table;
	}

	/**
	 * 格式化日期
	 * @param calendar 日期
	 * @param format 格式类型
	 * @return 时间字符串
	 */
	public static String formatDate(Calendar calendar, String format){
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(calendar.getTime());
	}

	/**
	 * 将字符串以 {charset} 格式写入文件中
	 * @param file 需要写入的文件
	 * @param data 字符串数据
	 * @param charset 字符集
	 */
	public static void writeStringToFile(File file, String data, Charset charset) {
		IoUtils.write(data.getBytes(charset), file);
	}

	/**
	 * 判断当前字符串是否为空
	 * @param s 验证的字符串
	 * @return 结果
	 */
	public static boolean isNotBlank(String s){
		return StringUtils.isNotBlank(s);
	}

	/**
	 * 在字符串右侧拼接空格到len的长度
	 * @param start q起始字符串
	 * @param len 拼接长度
	 * @return 拼装后的字符串
	 */
	public static String rightPad(String start, int len){
		return rightPad(start, len, " ");
	}

	/**
	 * 在字符串右侧拼接{padStr}到len的长度
	 * @param start q起始字符串
	 * @param len 拼接长度
	 * @param padStr 不足长度 拼接字符串
	 * @return 拼装后的字符串
	 */
	public static String rightPad(String start, int len, String padStr){
		return StringUtils.rightPad(start, len, padStr);
	}

	/**
	 * 打开文件输出流
	 * @param file 文件
	 * @return 流
	 * @throws IOException
	 */
	public static OutputStream openOutputStream(File file) throws IOException {
		if (file.exists()) {
			if (file.isDirectory() || !file.canWrite()) {
				return null;
			}
		}else{
			File parent = file.getParentFile();
			if (parent != null) {
				parent.mkdirs();
			}
		}
		return new FileOutputStream(file);
	}

}
